<template>
  <div class="boxx">
    <h1 style="color:#fff;text-align: center; padding: 10px 0;">嗨购商城后台管理系统</h1>
    <p style="color:#fff;text-align: center;">Hi Shopping Mall's background management system</p>
    <div class="loginbox">
      <h3 style="text-align: center;">登录页面</h3>
      <el-form :model="user" ref="ruleFormRef" class="demo-ruleForm" :size="formSize" status-icon>

        <el-form-item label="用户名" required>
          <el-input v-model="user.adminname"></el-input>
        </el-form-item>

        <el-form-item label="密码" required>
          <el-input v-model="user.password" type="password" placeholder="Please input password" show-password />
        </el-form-item>

        <el-form-item>
          <el-button @click="loginfun">登录</el-button>
          <el-button @click="fun">清空</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script setup lang="ts">
import 'element-plus/dist/index.css'
import { ElMessage } from 'element-plus';
import service from '../ulit/service'
import { reactive, ref } from 'vue'
import type { FormInstance, FormRules } from 'element-plus'
import { useRouter } from 'vue-router';

const formSize = ref('default')
const $router = useRouter();

//定义
interface Iuser {
  adminname: string,
  password: string
}
const user = reactive<Iuser>({
  adminname: "admin",
  password: "123456"
})
//清空
const fun = () => {
  user.adminname = '',
    user.password = ''
}
//登录
const loginfun = () => {
  if (user.adminname && user.password) {
    service({
      url: "/admin/login",
      method: "post",
      data: user
    }).then(res => {
      switch (res.data.code) {
        case "200": {
          ElMessage({
            message: "登录成功！",
            type: "success"
          });
          // 存储当前用户名
          sessionStorage.setItem("username", user.adminname)
          // 存储token
          sessionStorage.setItem("token", res.data.data.token)
          // 存储当前用户的权限
          sessionStorage.setItem("grants", JSON.stringify(res.data.data.checkedkeys))
          $router.push("/admin")
          break;
        }
        case "10003": {
          ElMessage({
            message: "密码错误！",
            type: "error"
          });
          break;
        }
        case "10005": {
          ElMessage({
            message: "未注册！",
            type: "error"
          });
          break;
        }
      }
    })
  } else {
    ElMessage({
      message: "用户名密码不为空！",
      type: "error"
    });
  }
}

</script>

<style scoped>
.boxx {
  width: 100%;
  height: 100%;
  background-image: url(../assets/login.jpg);
  background-size: 100% 100%;
  overflow: hidden;

}

.loginbox {
  width: 500px;
  height: 300px;
  margin: auto;
  margin-top: 80px;
  background: rgba(0, 0, 0, 0.2);
  border-radius: 10px;
}

.el-form {
  display: flex;
  flex-direction: column;
  justify-content: space-evenly;
  align-items: center;
  height: 300px;
}

.el-input {
  width: 300px;
}
</style>